//
//  wordsUpAndDown.m
//  i18n
//
//  Created by Earus on 11/27/11.
//  Copyright (c) 2011 patrick.decaluwe@student.uclouvain.be. All rights reserved.
//

#import "wordsUpAndDown.h"

@implementation wordsUpAndDownViewController

@synthesize quizWordLabel;
@synthesize prevWordLabel;
@synthesize prevWordDescText;

@synthesize upButton;
@synthesize downButton;

const int TAG_CONGRATULATION = 1;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        shouldDismiss = FALSE;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    NSString *filename = [[NSUserDefaults standardUserDefaults] stringForKey:@"selected_wordset"];
    if (filename == nil || [filename length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"에러" message:@"단어장을 먼저 선택해주시기 바랍니다." delegate:nil cancelButtonTitle:@"확인" otherButtonTitles:nil];
        
        [alert show];
        
        shouldDismiss = YES;
        return;
    }
    
    NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [NSString stringWithFormat:@"%@/%@", [dirArray objectAtIndex:0], filename];

    if ([[NSFileManager defaultManager] fileExistsAtPath:path] == NO) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"에러" message:@"단어장이 없습니다. 단어장을 다시 선택해주세요." delegate:nil cancelButtonTitle:@"확인" otherButtonTitles:nil];
        
        [alert show];
        
        shouldDismiss = YES;
        return;
    }
    
    [self loadLearnedWords];
    [self prepareWordsFromFile:path];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewDidAppear:(BOOL)animated
{
    if (shouldDismiss == YES)
        [self dismissModalViewControllerAnimated:YES];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Up and Down

- (void)prepareWordsFromFile:(NSString *)path
{
    NSURL *xmlURL = [[NSURL fileURLWithPath:path] autorelease];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];

    wordList = [[NSMutableArray alloc] init];
    meaningList = [[NSMutableArray alloc] init];

    [parser setDelegate:self];
    [parser parse];
}

- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
    attributes:(NSDictionary *)attributeDict {  
    
    if ([elementName isEqualToString:@"word"]) {
        NSString *word = [NSString stringWithFormat:@"%@", [attributeDict objectForKey:@"text"]];
        NSString *meaning = [NSString stringWithFormat:@"%@", [attributeDict objectForKey:@"meaning"]];

        NSLog(@"parsed word = %@", word);

        [wordList addObject:word];
        [meaningList addObject:meaning];
    }
}

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    [self nextRound];
}

- (BOOL)isAvailableWord:(NSString *)word
{
    for (int i = 0; i < [learnedList count]; i++) {
		NSMutableDictionary *learnedWord = [learnedList objectAtIndex:i];
        
		if ([learnedWord objectForKey:word] != nil && [learnedWord objectForKey:word] == 0) {
            return NO;
        }
    }
    
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([alertView tag] == TAG_CONGRATULATION) {
        [self dismissModalViewControllerAnimated:YES];
    }
}

- (void)nextRound
{
    int knownWordCount = 0;
    int wordIndex;
    
    for (int i = 0; i < [wordList count]; i++) {
        for (int j = 0; j < [learnedList count]; j++) {
            NSMutableDictionary *learnedWord = [learnedList objectAtIndex:j];
            
            if ([learnedWord objectForKey:[wordList objectAtIndex:i]] != nil && [[learnedWord objectForKey:[wordList objectAtIndex:i]] intValue] == 0) {
                knownWordCount++;
                break;
            }
        }
    }
    
    if ([wordList count] == knownWordCount) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"축하합니다." message:@"현재 단어장의 모든 단어를 학습하셨습니다." delegate:self cancelButtonTitle:@"확인" otherButtonTitles:nil];
        
        [alert setTag:TAG_CONGRATULATION];
        [alert show];
        
        return;
    }
    
    while (YES) {
        wordIndex = arc4random() % [wordList count];
        
        if ([self isAvailableWord:[wordList objectAtIndex:wordIndex]] == YES) {
            break;
        }
    }

    int prevWordIndex = [wordList indexOfObject:[quizWordLabel text]];
    
    if (prevWordIndex != NSNotFound) {
        [prevWordLabel setText:[quizWordLabel text]];
        [prevWordDescText setText:[meaningList objectAtIndex:prevWordIndex]];
    }

    [quizWordLabel setText:[wordList objectAtIndex:wordIndex]];
}

- (void)showNextRoundAnimation
{
    CGRect dstFrame = prevWordLabel.frame;
    
    prevWordDescText.alpha = 0;
    prevWordLabel.alpha = 1;
    prevWordLabel.frame = quizWordLabel.frame;
    
    [UIView beginAnimations:@"" context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(didPrevWordTranslateFinish)];
    prevWordLabel.frame = dstFrame;
    [UIView commitAnimations];
}

- (void)didPrevWordTranslateFinish {
    prevWordDescText.alpha = 0;
    [UIView beginAnimations:@"" context:nil];
    [UIView setAnimationDuration:0.2];
    prevWordDescText.alpha = 1;
    [UIView commitAnimations];
}

- (void)addLearnedWord:(NSString*)word userKnows:(BOOL)userKnows
{
    for (int i = 0; i < [learnedList count]; i++) {
		NSMutableDictionary *learnedWord = [learnedList objectAtIndex:i];

		if ([learnedWord objectForKey:word] != nil) {
            int importance = [[learnedWord objectForKey:word] intValue];
            
            if (userKnows == YES) {
                // 아는 단어면
                [learnedWord setObject:[NSNumber numberWithInt:0] forKey:word];
            } else {
                // 모르는 단어면
                [learnedWord setObject:[NSNumber numberWithInt:++importance] forKey:word];
            }
            
            [self saveLearnedWords];
            return;
        }
	}
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    int importance = (userKnows == YES) ? 0 : 1;
    [dict setObject:[NSNumber numberWithInt:importance] forKey:word];
    [learnedList addObject:dict];
    
    [self saveLearnedWords];
}

- (NSString *)getLearnedListFilePath
{
    NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [NSString stringWithFormat:@"%@/learnedlist.plist", [dirArray objectAtIndex:0]];

    return path;
}

- (void)loadLearnedWords
{
    NSString *path = [self getLearnedListFilePath];
	learnedList = [[NSMutableArray alloc] initWithContentsOfFile:path];
    
    if (learnedList == nil)
        learnedList = [[NSMutableArray alloc] init];
}

- (void)saveLearnedWords
{
    NSString *path = [self getLearnedListFilePath];
    [learnedList writeToFile:path atomically:YES];
}

- (IBAction)touchHomeAction:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)touchUpAction:(id)sender
{
    [self addLearnedWord:quizWordLabel.text userKnows:YES];
    
    [self showNextRoundAnimation];
    [self nextRound];
}

- (IBAction)touchDownAction:(id)sender
{
    [self addLearnedWord:quizWordLabel.text userKnows:NO];
    
    [self showNextRoundAnimation];
    [self nextRound];
}

@end